<?php
namespace app\index\controller;

use app\common\controller\Front;
use think\Loader;

class Search extends Front
{
    // sphinx模型对象
    private $_model_sphinx_search;

    /**
     * 关键字搜索
     *
     * @return html
     */
    public function index()
    {
        $search_key = $this->request->param('key/d', 0); // 0默认排序，1销量 ， 2人气 ，3价格
        $search_order = $this->request->param('order/d', 0); // 0是默认无排序，1是低到高，2是高到低
        $search_area_id = $this->request->param('area_id/d', 0); // 默认地区0
        if ($search_area_id) {
            //$area = \Area::get_by_id($search_area_id);
            $area = rpc('common/common/one',['area',['area_id'=>$search_area_id],['field'=>'area_name']]);
            if ($area) {
                $search_area = $area['area_name']; // 搜索地区0
            } else {
                $search_area = ''; // 搜索地区
            }
        }
        $curpage = $this->request->param('curpage/d', 1); // 当前页，默认第一页
        $search_keyword = $this->request->param('keyword/s', ''); // 搜索的关键字,超过限定长度则截取60位
        $page_size = config('limit_goods_cate');
        $page_size = $page_size ?  : 24;
        if (mb_strlen($search_keyword, 'UTF-8') > 60) {
            $search_keyword = mb_substr($search_keyword, 0, 60, 'UTF-8');
        }
        
        // 字段
        $condition = array();
        // 处理排序
        $order = 'goods_common.id desc';
        if (in_array($search_key, [
            '1',
            '2',
            '3'
        ])) {
            $sequence = $search_order == '1' ? 'asc' : 'desc';
            switch ($search_key) {
                case '1':
                    $order = 'goods_common_static.last_30_salenum';
                    break;
                case '2':
                    $order = 'goods_common_static.click_num';
                    break;
                case '3':
                    $order = 'goods_common.goods_price';
                    break;
            }
            $order .= ' ' . $sequence;
        }
        
        if (config('sphinx_open')) {
            $this->_model_sphinx_search = Loader::model('Sphinx');
        }
        if ($search_keyword != '' && config('sphinx_open') && $this->_model_sphinx_search->getStatus()) {
            // 执行sphinx
            // 地区筛选
            $sphinx_keyword = $search_keyword;
            if (! empty($search_area)) {
                $sphinx_keyword = '(' . $search_keyword . ')&(' . $area['area_name'] . ')';
            }
            
            // 设置sphinx索引串
            $condition = [
                'key' => $search_key,
                'order' => $search_order,
                'keyword' => $sphinx_keyword
            ];
            $this->_model_sphinx_search->setSphinxKeyword($sphinx_keyword);
            list ($sphinx_ids, $sphinx_count, $sphinx_total) = $this->_model_sphinx_search->indexerSearch($condition, 'goods', $page_size);
            $goods_list = $sphinx_ids;
            $total_num = $sphinx_total;
        } else {
            $where = ' 1=1 and goods_verify=1 and goods_state=1';
            if ($search_keyword != '') {
                $where .= ' and (goods_common.goods_name like "%' . $search_keyword . '%" or goods_common.goods_jingle like "%' . $search_keyword . '%" or goods_common.spec_value like "%' . $search_keyword . '%")';
            }
            if (! empty($search_area)) {
                // 地区筛选
                $tmp_str = '%' . $search_area . '%';
                $where .= ' and (goods_common.goods_name like "' . $tmp_str . '" or goods_common.goods_jingle like "' . $tmp_str . '" or goods_common.spec_value like "' . $tmp_str . '")';
            }
            // 拼装sql语句
            $sql = 'select goods_common.id from mall_goods_common goods_common left join mall_goods_common_static goods_common_static on goods_common.id=goods_common_static.commonid' . ' where ' . $where . ' order by ' . $order . ' limit ' . ($curpage - 1) * $page_size . ',' . $page_size;
            $goods_list = rpc('common/common/sql', [
                $sql
            ]);
            $goods_list = array_map('reset', $goods_list);
            // 拼装sql语句
            $sql = 'select count(id) as num from mall_goods_common goods_common where ' . $where;
            $total_num = rpc('common/common/sql', [
                $sql
            ]);
            $total_num = $total_num[0]['num'];
        }
        // 月销量
        $salenum = 0;
        // 月参数
        $begin = date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y")));
        $end = date("Y-m-d", mktime(23, 59, 59, date("m"), date("t"), date("Y")));
        // 商品多图
        if (! empty($goods_list)) {
            $commonid_array = array_unique($goods_list); // 商品公共id数组
            $storeid_array = array(); // 店铺id数组
            $goodsid_array = array(); // 公共内容的商品代表数组
                                      // 拼装sql语句
            $where = ' 1=1 and goods_verify=1 and goods_state=1';
            if ($search_keyword != '') {
                $where .= ' and (goods_name like "%' . $search_keyword . '%" or goods_jingle like "%' . $search_keyword . '%" or goods_spec like "%' . $search_keyword . '%")';
            }
            if (! empty($search_area)) {
                // 地区筛选
                $tmp_str = '%' . $search_area . '%';
                $where .= ' and (goods_name like "' . $tmp_str . '" or goods_jingle like "' . $tmp_str . '" or goods_spec like "' . $tmp_str . '")';
            }
            $sql = 'select id ,commonid from mall_goods where commonid in (' . trim(implode(',', $commonid_array), ',') . ') and ' . $where . ' group by commonid ';
            $goodsid_tmp_array = rpc('common/common/sql', [
                $sql
            ]);
            if (! empty($goodsid_tmp_array)) {
                foreach ($goodsid_tmp_array as $key => $val) {
                    $goodsid_array[$val['commonid']] = $val['id'];
                }
            }
            // 拼装sql语句
            $where = " goods_common.id in (" . trim(implode(',', $commonid_array), ',') . ')';
            $sql = 'select goods_common.id,goods_common.goods_name,goods_common.goods_jingle,goods_common.goods_jingle,goods_common.goods_jingle,goods_common.goods_image,goods_common.goods_price, '
                    .'goods_common.goods_price,goods_common.goods_unit,goods_common.store_name,goods_common.store_id,'
                    .'goods_common_static.evaluation_scores, goods_common_static.total_salenum, goods_common_static.last_30_salenum, goods_common_static.click_num from mall_goods_common goods_common left join mall_goods_common_static goods_common_static on goods_common.id=goods_common_static.commonid' 
                    . ' where ' . $where . " order by " . $order;
            $goods_common_list = rpc('common/common/sql', [
                $sql
            ]);
            if (! empty($goods_common_list)) {
                foreach ($goods_common_list as $key => $val) {
                    $storeid_array[] = $val['store_id'];
                }
            }
            $storeid_array = array_unique($storeid_array);
            // 店铺
            $store_list = $this->db_lists('store', [
                'id' => [
                    'in',
                    $storeid_array
                ]
            ], [
                'field' => 'id,name,member_id,qq'
            ]);
            $store_list = reset_by_key($store_list, 'id'); // 以ID重新排列       
            foreach ($goods_common_list as $key => $value) {
                // 店铺的开店会员编号
                $store_id = $value['store_id'];
                $goods_common_list[$key]['member_id'] = isset($store_list[$store_id]['member_id']) ? $store_list[$store_id]['member_id'] : 0;
                // 将关键字置红
                if (config('sphinx_open') && isset($search_keyword)) {
                    $tmp_keyword = str_replace(' ', '', $search_keyword);
                    $tmp_keyword = str_replace('$', '', $tmp_keyword);
                    $tmp_keyword = str_replace('^', '', $tmp_keyword);
                    $tmp_keyword = array_unique($this->mb_str_split($tmp_keyword));
                    // sphinx搜索所得
                    $reg_match_from1 = array();
                    $reg_match_to1 = array();
                    $reg_match_from2 = array();
                    $reg_match_to2 = array();
                    foreach ($tmp_keyword as $key1 => $val1) {
                        if (in_array($val1, array(
                            '.',
                            '*',
                            '+',
                            '-',
                            '?',
                            '=',
                            '!',
                            ':',
                            '|',
                            '\\',
                            '/',
                            '(',
                            ')',
                            '[',
                            ']',
                            '{',
                            '}'
                        ))) {
                            $reg_match_from1[] = $reg_match_from2[] = "/(\\" . $val1 . ")/i";
                        } else {
                            $reg_match_from1[] = $reg_match_from2[] = "/(" . $val1 . ")/i";
                        }
                        $reg_match_to1[] = '^\\1$';
                        $reg_match_to2[] = '^\\1$';
                    }
                    // 去除特殊符号^$
                    $value['goods_name'] = str_replace('^', '', $value['goods_name']);
                    $value['goods_name'] = str_replace('$', '', $value['goods_name']);
                    $value['goods_jingle'] = str_replace('^', '', $value['goods_jingle']);
                    $value['goods_jingle'] = str_replace('$', '', $value['goods_jingle']);
                    $goods_common_list[$key]['goods_name_highlight'] = preg_replace($reg_match_from1, $reg_match_to1, $value['goods_name']);
                    $goods_common_list[$key]['goods_jingle_highlight'] = preg_replace($reg_match_from2, $reg_match_to2, $value['goods_jingle']);
                    $goods_common_list[$key]['goods_name_highlight'] = str_replace('^', '<font style="color:red;">', $goods_common_list[$key]['goods_name_highlight']);
                    $goods_common_list[$key]['goods_name_highlight'] = str_replace('$', '</font>', $goods_common_list[$key]['goods_name_highlight']);
                    $goods_common_list[$key]['goods_jingle_highlight'] = str_replace('^', '<font style="color:red;">', $goods_common_list[$key]['goods_jingle_highlight']);
                    $goods_common_list[$key]['goods_jingle_highlight'] = str_replace('$', '</font>', $goods_common_list[$key]['goods_jingle_highlight']);
                    unset($tmp_keyword);
                    unset($reg_match_from1);
                    unset($reg_match_to1);
                    unset($reg_match_from2);
                    unset($reg_match_to2);
                } elseif (is_string($search_keyword)) {
                    // 一般查询所得
                    $goods_common_list[$key]['goods_name_highlight'] = str_replace($search_keyword, '<font style="color:#f00;">' . $search_keyword . '</font>', $value['goods_name']);
                    $goods_common_list[$key]['goods_jingle_highlight'] = str_replace($search_keyword, '<font style="color:#f00;">' . $search_keyword . '</font>', $value['goods_jingle']);
                } else {
                    $goods_common_list[$key]['goods_name_highlight'] = $value['goods_name'];
                    $goods_common_list[$key]['goods_jingle_highlight'] = $value['goods_jingle'];
                }
                // 添加商家信息
                $goods_common_list[$key]['qq'] = isset($store_list[$store_id]) ? $store_list[$store_id]['qq'] : '';
                $goods_common_list[$key]['store_name'] = isset($store_list[$store_id]) ? $store_list[$store_id]['name'] : '';

                // 添加公共内容的代表商品id
                $goods_common_list[$key]['goods_id'] = isset($goodsid_array[$value['id']]) ? $goodsid_array[$value['id']] : 0;
            }
        }
        // 排序生成url用
        $query = [
            'key' => $search_key,
            'order' => $search_order,
            'area_id' => $search_area_id,
            'keyword' => $search_keyword
        ];
        // 分页渲染内容
        $option = [
            'var_page' => 'curpage',
            'path' => '?s=/index/search/index',
            'query' => $query
        ];
        $page = \Page::make($goods_common_list, $page_size, $curpage, $total_num, false, $option);
        
        // 加载地区
        $list_area = $this->db_lists('area','',['page'=>'1,5000']);
        $this->view->assign('list_area', json_encode($list_area));
        
        $this->view->assign('search_key', $search_key);
        $this->view->assign('search_order', $search_order);
        $this->view->assign('query', $query);
        $this->view->assign('total_num', $total_num);
        $this->view->assign('return_area_id', $search_area_id);
        $this->view->assign('total_num', $total_num);
        $this->view->assign('page', $page);
        $this->view->assign('goods_common_list', $goods_common_list);
        if ($search_keyword != '') {
            $this->view->assign('show_keyword', $search_keyword);
        }
        
        $this->view->assign('_page', [
            'title' => '爱员工官网搜索',
            'name' => $search_keyword
        ]);
        return $this->view->fetch('goods/index');
    }

    /**
     * Convert a string to an array
     *
     * @param string $str
     * @param number $split_length
     * @return multitype:string
     */
    private function mb_str_split($str, $split_length = 1, $charset = "UTF-8")
    {
        if (func_num_args() == 1) {
            return preg_split('/(?<!^)(?!$)/u', $str);
        }
        if ($split_length < 1)
            return false;
        $len = mb_strlen($str, $charset);
        $arr = array();
        for ($i = 0; $i < $len; $i += $split_length) {
            $s = mb_substr($str, $i, $split_length, $charset);
            $arr[] = $s;
        }
        return $arr;
    }
}
